<?php
/**
 * appRain v 0.1.x
 *
 * LICENSE
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.opensource.org/licenses/mit-license.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@apprain.com so we can send you a copy immediately.
 *
 * @copyright  Copyright (c) 2010 appRain, Inc. (http://www.apprain.com)
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 *
 * HELP
 *
 * Official Website
 * http://www.apprain.com/
 *
 * Download Link
 * http://www.apprain.com/download
 *
 * Documents Link
 * http ://www.apprain.com/documents
 */
class pcjobsController extends appRain_Base_Core
{
    public $name = 'Pcjobs';

	public function __preDispatch(){}

	public function createAction($srcType="")
	{
		$this->setAdminTab('photoclipingnavuser');
		$this->addons = array('uploadify','validation');

		if(!empty($this->data))
		{
			$this->layout ="blank";
			$this->data['Job']['ftp_loc']= isset($this->data['Job']['ftp_loc']) ? $this->data['Job']['ftp_loc'] : "";

			if($this->data['Job']['title'] == "") //  || $this->data['Job']['ftp_loc'] ==""
			{
				echo App::Load("Module/Cryptography")->jsonEncode(array(
                                                                    "_status" =>'Error',
                                                                    "_message"=>"Enter value in Title, Ftp Location and num_images"
                                                              ));
			}
			/*else if(!is_numeric($this->data['Job']['num_images']))
			{
				echo App::Load("Module/Cryptography")->jsonEncode(array(
                                                                    "_status" =>'Error',
                                                                    "_message"=>"Number of images must be numerice"
                                                              ));
				exit;
			}*/
			else
			{

				if(isset($this->data['Job']['upload_type']))
				{
					App::Session()->Write('SelectJob',$this->data['Job']);
					$loc = $this->baseUrl("/pcjobs/create/{$this->data['Job']['upload_type']}");
				}
				else
				{
					$token = time();
					$this->data['Job']['client_id'] = App::getUserStatusId();
					$this->data['Job']['token'] = $token;
					$this->data['Job']['downloadtype'] =  ('ftp' == strtolower($srcType)) ? 'Ftp' : 'File';
					$this->data['Job']['created'] = time();
					App::Model('Job')->Save($this->data);

					$loc = $this->baseUrl("/pcjobs/uploadfiles/{$token}");
				}

				echo App::Load("Module/Cryptography")->jsonEncode(array("_status" =>'Redirect',"_location"=> $loc));
				exit;
			}
		}

		$SelectJob = App::Session()->Read('SelectJob');
		$this->set('SelectJob',$SelectJob);
		$this->set('srcType',$srcType);
	}

	public function manageAction($action="view",$id=null)
	{
		$Data = Array();
		$userId = App::getUserStatusId();
		$jobsrc = App::Session()->Read('jobsrc');

		if($userId) $this->setAdminTab('photoclipingnavuser');
		else $this->setAdminTab('photoclipingnavsuper');

		if(isset($this->data['Search']))
		{
			App::Session()->Write('jobsrc',$this->data['Search']);
			$this->redirect("/pcjobs/manage");
			exit;
		}

		if($action == "view")
		{
			if(isset($id))
			{
				$Data = App::Model('Job')->findById($id);
			}
			else
			{
                 $this->addons = array('row_manager');
				$s = isset($_GET['s'])? $_GET['s'] : 'id';
				$o = isset($_GET['o'])? $_GET['o'] : 'DESC';
				$this->set('o',$o);

				$default_pagination  = App::Config()->siteInfo("default_pagination");

				$cnd = "1 ";
				if(isset($jobsrc['str']) && $jobsrc['str']!="")$cnd .= " AND title LIKE '%{$jobsrc['str']}%' ";

				if(isset($jobsrc['startdate']) && $jobsrc['startdate']!="Start Date" && $jobsrc['startdate']!="" &&
					isset($jobsrc['enddate']) && $jobsrc['enddate']!='End Date' && $jobsrc['enddate']!='')
				{
					$starttime = strtotime("{$jobsrc['startdate']} 12am");
					//$endtime = strtotime("{$jobsrc['enddate']} 12PM");
					$endtime = strtotime("{$jobsrc['enddate']} 12pm") + (12*60*60);
					$cnd .= " AND (created >= {$starttime} AND created <= {$endtime}) ";
				}

				if($userId)
				{
					$Data = App::Model('Job')->paging("$cnd AND client_id={$userId} ORDER by {$s} {$o}",$default_pagination);
				}
				else
				{	
					if(isset($jobsrc['member']) && $jobsrc['member']!="")$cnd .=" AND client_id = {$jobsrc['member']} ";
					$Data = App::Model('Job')->paging("{$cnd} ORDER by {$s} {$o}",$default_pagination);
				}
			}
		}
		else if($action == "update")
		{
			$total = 0;
			if(isset($this->data['Item']) && !empty($this->data['Item']))
			{foreach($this->data['Item']["rate"] as $FId=>$Rate)
			{
				$total += $Rate;
				App::Model('File')->setRate($Rate)->setId($FId)->Save();
			}}

			$Job = App::Model('Job')->findById($id);

			if(strtolower($this->data['Job']['status']) == 'started' && $Job['start_date']=="")
			{
				App::Model('Job')->setStart_date(time());
			}
			else if($this->data['Job']['status'] == 'Complete' && !$Job['end_date'])
			{
				App::Model('Job')->setEnd_date(time());
			}

			$total = isset($this->data['Job']['total']) ? $this->data['Job']['total'] : $total;
			App::Model('Job')
			   ->setStatus($this->data['Job']['status'])
			   ->setDownload_link($this->data['Job']['download_link'])
			   ->setTotal($total)
               ->setPaymentstatus($this->data['Job']['paymentstatus'])
			   ->setId($id)->Save();

			if($this->data['Job']['status']=='Priceing')
			{
				App::Component('Photocliping')->helper('Data')->sendEmail('QutationSubmitted',array("jobid"=>$id));
			}
			else if($this->data['Job']['status']=='Complete')
			{
				App::Component('Photocliping')->helper('Data')->sendEmail('JobCompleted',array("jobid"=>$id));
			}
			App::Module('Notification')->Push('Job Updated successfully.');
			$this->redirect("/pcjobs/manage/view/{$id}");
			exit;
		}

		$this->set('Data',$Data);
		$this->set('action',$action);
		$this->set('id',$id);
		$this->set('jobsrc',$jobsrc);
		$this->set('userId',$userId);

	}

	public function uploadfilesAction($token=null)
	{
		$this->layout = "blank";

		if(isset($token))
		{
			$id = App::Component('PhotoCliping')
					 ->Helper('Data')
					 ->FinalizeJobById($token);

			App::Module('Notification')->Push('Job submitted successfully and waiting for quotation');

			$this->redirect("/pcjobs/manage/view/{$id}");
			exit;
		}

		if (!empty($_FILES))
		{
			$id = App::Component('PhotoCliping')
					->Helper('Data')
					->setClientId($_REQUEST['clientid'])
					->setServiceId($_REQUEST['services'])
					->setTitle($_REQUEST['title'])
					->setToken($_REQUEST['token'])
					->setDescription($_REQUEST['description'])
					->setDeliveryTime($_REQUEST['deliverytime'])
					->setDeliveryType($_REQUEST['deliverytype'])
					->createJobFirstInstanceGetId();

			$path = $this->baseDir("/uploads/photo/{$_REQUEST['token']}/");
			if(!file_exists($path))
			{
				App::Helper('Utility')->createDir($path);
			}

			$file = App::Helper('Utility')->upload($_FILES['Filedata'],$path);

			App::Model('File')
			   ->setJob_id($id)
			   ->setName($file['file_name'])
			   ->setCreated(time())
			   ->Save();

			echo "Upload done successfully.";
		}
	}

	public function downloadAction($link)
	{
		$link = base64_decode($link);
		$path = $this->rootDir("/download{$link}");

		if(file_exists($path))App::Helper('Utility')->download($path);
		else App::Helper("Config")->transfer($this->baseUrl("/"),"File does not exists! Please contact adminstrator");
		exit;
	}

	public function changestatusAction($status=null, $id=null)
	{
		if(isset($status) && isset($id))
		{
			App::Model('Job')->setStatus($status)->setId($id)->Save();

			if($status=='approved' || strtolower($status)=='started')
			{
				App::Model('Job')->setStart_date(App::Helper('Date')->getTime())->setId($id)->Save();
				App::Component('Photocliping')->helper('Data')->sendEmail('JobApproved',array("jobid"=>$id));
			}
			App::Module('Notification')->Push('Job Status Changed successfully');
			$this->redirect("/pcjobs/manage/view/{$id}");
			exit;
		}
	}

	public function paymentsAction()
	{
		$this->setAdminTab('photoclipingnavsuperpayment');
		$jobsrc = App::Session()->Read('paysrc');


		if(isset($this->data['Search']))
		{
			App::Session()->Write('paysrc',$this->data['Search']);
			$this->redirect("/pcjobs/payments");
			exit;
		}

		$cnd = "1 ";
		if(isset($jobsrc['str']) && $jobsrc['str']!="" && $jobsrc['str'] !='type')$cnd .= " AND processor = '{$jobsrc['str']}' ";
		if(isset($jobsrc['member']) && $jobsrc['member']!="")$cnd .=" AND client_id = {$jobsrc['member']} ";

		if(isset($jobsrc['startdate']) && $jobsrc['startdate']!="Start Date" && $jobsrc['startdate']!="" &&
			isset($jobsrc['enddate']) && $jobsrc['enddate']!='End Date' && $jobsrc['enddate']!='')
		{
			$starttime = strtotime("{$jobsrc['startdate']}");
			//$endtime = strtotime("{$jobsrc['enddate']} 12PM");
			$endtime = strtotime("{$jobsrc['enddate']} 12pm") + (12*60*60);
			$cnd .= " AND (order_date >= {$starttime} AND order_date <= {$endtime}) ";
		}

		$s = isset($_GET['s'])? $_GET['s'] : 'id';
		$o = isset($_GET['o'])? $_GET['o'] : 'DESC';
		$this->set('o',$o);

		$Payments = App::Model('Payment')->paging("$cnd ORDER BY {$s} {$o}",App::Config()->siteInfo("default_pagination"));
		$this->set('Payments',$Payments);
		$this->set('jobsrc',$jobsrc);
	}


	public function paymentAction($client_id=null,$action=null,$job_id=null)
	{
		$this->setAdminTab('photoclipingnavsuper');

		if($action == 'adjustpayment')
		{
			if(isset($client_id) && isset($job_id))
			{
				App::Component('Photocliping')->Helper('Data')->adjustPayment($client_id,$job_id);
			}

			$this->redirect("/pcjobs/manage/view/{$job_id}");
			exit;
		}


		if(!empty($this->data))
		{

			$Photocliping = App::Component('Photocliping')
								->Helper('Data')
								->setAmount($this->data['Payment']['amount'])
								->setProcessor($this->data['Payment']['processor'])
								->setOrder_date(strtotime($this->data['Payment']['order_date']))
								->setClientId($client_id);

			if($this->data['Payment']['action'] == 'Add')
			{

				$Photocliping->addPayment();
			}
			else
			{
			   $Photocliping->deductPayment();
			}

			App::Module('Notification')->Push("Payment {$this->data['Payment']['action']}ed successfully.");
			$this->redirect("/pcjobs/payment/{$client_id}");
			exit;
		}
		$account = App::Model('Account')->findByClient_id($client_id);
		$this->set('account',$account);
		$this->setClientId($client_id);
	}

	public function viewpaymentAction()
	{
		$this->setAdminTab('paymentsuser');
	}

	public $paypal_url = 'https://www.paypal.com/cgi-bin/webscr';
	public $paypal_sandbox_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
	public $payment_success_url = '/pcjobs/addapayment';
	public $payment_failed_url = '/pcjobs/paymentfailed';
	public $payment_notify_url = '/pcjobs/paypalipn';

	public function addapaymentAction()
	{
		$this->setAdminTab('paymentsuser');
		$accountData = App::Model('Account')->findByClient_id(App::getUserStatusId());
		$balance = isset($accountData['balance'])?$accountData['balance']:0;
		$this->setBalance($balance);

		if(!empty($this->data))
		{
			$this->layout = 'empty';
			$client_id = App::getUserStatusId();

			$PdoObj = App::Model('Payment')->setClient_id($client_id)
								 ->setProcessor('paypal')
								 ->setOrder_date(time())
								 ->setOrder_number(time())
								 ->setTotal($this->data['Payment']['amount'])
								 ->Save();

			// BING PAYPAL
			App::setUserStatusId(0);
			$Config = 	App::Helper('Config');
			$siteInfo = $Config->siteInfo();

			if($siteInfo['paypal_mode'] == 'Sandbox') App::Plugin("Paypal_Standard")->paypal_url = $this->paypal_sandbox_url;
			else App::Plugin("Paypal_Standard")->paypal_url = $this->paypal_url;

			App::Plugin("Paypal_Standard")->add_field('business', $siteInfo['paypal_payment_email'])
									  ->add_field('return', $Config->baseUrl($this->payment_success_url))
									  ->add_field('cancel_return', $Config->baseUrl($this->payment_failed_url))
									  ->add_field('notify_url', $Config->baseUrl($this->payment_notify_url))
									  ->add_field('currency_code', 'USD')
									  ->add_field('item_name', $siteInfo['site_title'])
									  ->add_field('amount', $this->data['Payment']['amount'])
									  ->add_field('custom',$PdoObj->getId())
									  ->submit_paypal_post();

		}
	}

	public function paypalipnAction($id)
	{
		App::setUserStatusId(0);
		$siteInfo = App::Helper('Config')->siteInfo();
		if($siteInfo['paypal_mode'] == 'Sandbox') App::Plugin("Paypal_Standard")->paypal_url = $this->paypal_sandbox_url;
		else App::Plugin("Paypal_Standard")->paypal_url = $this->paypal_url;

		if(App::Plugin("Paypal_Standard")->validate_ipn())
		{
			$id = App::Plugin("Paypal_Standard")->ipn_data['custom'];
			$PData = App::Model('Payment')->findById($id);

			if(!empty($PData))
			{
				//if($PData['status'] != 'Success')
				{
					$accountData = App::Model('Account')->findByClient_id($PData['client_id']);

					$id = isset($accountData['id'])?$accountData['id']:null;
					$balance = isset($accountData['balance'])?($accountData['balance']+$PData['total']):$PData['total'];
					$created = isset($accountData['created'])?$accountData['created']:time();
					$updated = time();
					$modified = time();

					// Update Balance
					App::Model('Account')
						->setId($id)
						->setClient_id($PData['client_id'])
						->setBalance($balance)
						->setCreated($created)
						->setUpdated($updated)
						->setModified($modified)
						->Save();

					App::Module('Log')->Write("\${$PData['total']} Payment added by Paypal. Client id: {$PData['client_id']}");
					App::Component('Photocliping')->Helper('Data')->adjustPayment($PData['client_id']);
				}
			}
		}
	}

	public function paymentfailedAction()
	{
		pre("Payment Failed");
	}
}
